<!DOCTYPE HTML>
<html lang="zh-CN">


<head>
    <meta charset="utf-8">
    <meta name="keywords" content="1143.最长公共子序列（longestCommonSubsequence 简称LCS 问题）, 湮灭星空,博客,Python,后端">
    <meta name="description" content="1143.最长公共子序列（longestCommonSubsequence 简称LCS 问题）
问题
给定两个字符串 text1 和 text2，返回这两个字符串的最长公共子序列。
一个字符串的 子序列 是指这样一个新的字符串：它是由原字符">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <title>1143.最长公共子序列（longestCommonSubsequence 简称LCS 问题） | 湮灭星空</title>
    <link rel="icon" type="image/png" href="/favicon.png">

    <link rel="stylesheet" type="text/css" href="/libs/awesome/css/all.css">
    <link rel="stylesheet" type="text/css" href="/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/css/my.css">

    <script src="/libs/jquery/jquery.min.js"></script>

<link rel="alternate" href="/atom.xml" title="湮灭星空" type="application/atom+xml">
</head>

<body>
    <header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper head-container">
            <div class="brand-logo">
                <a href="/" class="waves-effect waves-light">
                    
                    <img src="/medias/logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">湮灭星空</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/" class="waves-effect waves-light">
      
      <i class="fas fa-home" style="zoom: 0.6;"></i>
      
      <span>首页</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/tags" class="waves-effect waves-light">
      
      <i class="fas fa-tags" style="zoom: 0.6;"></i>
      
      <span>标签</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/categories" class="waves-effect waves-light">
      
      <i class="fas fa-bookmark" style="zoom: 0.6;"></i>
      
      <span>分类</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/archives" class="waves-effect waves-light">
      
      <i class="fas fa-archive" style="zoom: 0.6;"></i>
      
      <span>归档</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/about" class="waves-effect waves-light">
      
      <i class="fas fa-user-circle" style="zoom: 0.6;"></i>
      
      <span>关于</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/contact" class="waves-effect waves-light">
      
      <i class="fas fa-comments" style="zoom: 0.6;"></i>
      
      <span>留言板</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/friends" class="waves-effect waves-light">
      
      <i class="fas fa-address-book" style="zoom: 0.6;"></i>
      
      <span>友链</span>
    </a>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="搜索" style="zoom: 0.85;"></i>
    </a>
  </li>
</ul>

<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/medias/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">湮灭星空</div>
        <div class="logo-desc">
            
            天下寥寥，苍生涂涂，诸子百家，唯我纵横
            
        </div>
    </div>

    

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-home"></i>
			
			首页
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/tags" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-tags"></i>
			
			标签
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/categories" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-bookmark"></i>
			
			分类
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/archives" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-archive"></i>
			
			归档
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/about" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-user-circle"></i>
			
			关于
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/contact" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-comments"></i>
			
			留言板
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/friends" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-address-book"></i>
			
			友链
		</a>
          
        </li>
        
        
    </ul>
</div>

        </div>

        
    </nav>

</header>

    



<div class="bg-cover pd-header post-cover" style="background-image: url('/medias/featureimages/2.jpg')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <div class="description center-align post-title">
                        1143.最长公共子序列（longestCommonSubsequence 简称LCS 问题）
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>




<main class="post-container content">

    
    <link rel="stylesheet" href="/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        padding-left: 20px;
    }

    .toc-widget .toc-title {
        margin: 35px 0 15px 0;
        padding-left: 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #toc-content .is-active-link::before {
        background-color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 15px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/tags/%E7%AE%97%E6%B3%95/">
                                <span class="chip bg-color">算法</span>
                            </a>
                        
                            <a href="/tags/%E6%9C%80%E9%95%BF%E5%85%AC%E5%85%B1%E5%AD%90%E4%B8%B2/">
                                <span class="chip bg-color">最长公共子串</span>
                            </a>
                        
                            <a href="/tags/LCS-%E9%97%AE%E9%A2%98/">
                                <span class="chip bg-color">LCS 问题</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fas fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/categories/Tech/" class="post-category">
                                Tech
                            </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-minus fa-fw"></i>发布日期:&nbsp;&nbsp;
                    2019-11-19
                </div>
                

                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-check fa-fw"></i>更新日期:&nbsp;&nbsp;
                    2020-01-30
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-file-word fa-fw"></i>文章字数:&nbsp;&nbsp;
                    1.8k
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-clock fa-fw"></i>阅读时长:&nbsp;&nbsp;
                    7 分
                </div>
                
				
                
                    <div id="busuanzi_container_page_pv" class="info-break-policy">
                        <i class="far fa-eye fa-fw"></i>阅读次数:&nbsp;&nbsp;
                        <span id="busuanzi_value_page_pv"></span>
                    </div>
				
            </div>
            
        </div>
        <hr class="clearfix">
        <div class="card-content article-card-content">
            <div id="articleContent">
                <h1 id="1143-最长公共子序列-longestcommonsubsequence-简称lcs-问题"><a class="header-anchor" href="#1143-最长公共子序列-longestcommonsubsequence-简称lcs-问题"></a>1143.最长公共子序列（longestCommonSubsequence 简称LCS 问题）</h1>
<h2 id="问题"><a class="header-anchor" href="#问题"></a>问题</h2>
<p>给定两个字符串 <code>text1</code> 和 <code>text2</code>，返回这两个字符串的最长公共子序列。</p>
<p>一个字符串的 子序列 是指这样一个新的字符串：它是由原字符串在不改变字符的相对顺序的情况下删除某些字符（也可以不删除任何字符）后组成的新字符串。<br>
例如，&quot;<code>ace</code>&quot; 是 “<code>abcde</code>” 的子序列，但 “<code>aec</code>” 不是 “<code>abcde</code>” 的子序列。两个字符串的「公共子序列」是这两个字符串所共同拥有的子序列。</p>
<p>若这两个字符串没有公共子序列，则返回 0。</p>
<p>示例 1:</p>
<p>输入：<code>text1</code> = “<code>abcde</code>”, <code>text2</code> = “<code>ace</code>”<br>
输出：3<br>
解释：最长公共子序列是 “<code>ace</code>”，它的长度为 3。<br>
示例 2:</p>
<p>输入：<code>text1</code> = “<code>abc</code>”, <code>text2</code> = “<code>abc</code>”<br>
输出：3<br>
解释：最长公共子序列是 “<code>abc</code>”，它的长度为 3。<br>
示例 3:</p>
<p>输入：text1 = “<code>abc</code>”, <code>text2</code> = “<code>def</code>”<br>
输出：0<br>
解释：两个字符串没有公共子序列，返回 0。</p>
<p>提示:</p>
<ul>
<li>1 &lt;= text1.length &lt;= 1000</li>
<li>1 &lt;= text2.length &lt;= 1000</li>
<li>输入的字符串只含有小写英文字符。</li>
</ul>
<blockquote>
<p>最长公共子序列：</p>
<p>一个给定的序列的子序列，就是将给定序列中的零个或多个元素去掉之后得到的结果，即可以不连续。</p>
<p>最长公共子串：</p>
<p>给定串中任意个连续的字符组成的子序列称为该串的子串。</p>
</blockquote>
<p><img src="https://klause-blog-pictures.oss-cn-shanghai.aliyuncs.com/2019-11-19-041324.png" alt="字序列和子串"></p>
<h2 id="动态规划"><a class="header-anchor" href="#动态规划"></a>动态规划</h2>
<p>求解 LCS（longest common subsequence）问题，不能使用暴力搜索方法。因为一个长度为 n 的序列，拥有 $2^n$ 个子序，它的时间复杂度是指数阶，太恐怖，所以需要借助动态规划的思想。</p>
<blockquote>
<p>动态规划算法通常用于求解具有某种最优性质的问题。在这类问题中，可能会有许多可行解。每一个解都对应一个值，我们希望找到具有最优值的解。</p>
<p>动态规划算法与分治法类似，基本思想是将待求解的问题分解成若干个子问题，先求解子问题，然后从这些子问题的解得到原问题的解。</p>
<p>与分治法不同的是，适合于动态规划的问题，经分解得到的子问题往往不是互相独立的。若用分治法来解这类问题，则分解得到的子问题数目太多，有些子问题会被计算很多次。如果能够保存已解决的子问题的答案，再在需要时取出答案，这样就可以避免大量重复计算，节省时间。</p>
<p>可以使用一个表来记录所有已解子问题的答案，无论该子问题以后是否会被用到，只要被计算过，就将其填入表中，这就是动态规划的基本思路。</p>
</blockquote>
<h2 id="特征分析"><a class="header-anchor" href="#特征分析"></a>特征分析</h2>
<p>解决 LCS 问题，需要把原问题分解成若干个子问题，所以需要刻画 LCS 的特征。</p>
<p>设A = A<sub>0</sub>, A<sub>1</sub>, … , A<sub>m</sub> 、B = B<sub>0</sub>, B<sub>1</sub>, … , B<sub>n</sub> 、Z = Z<sub>0</sub>, Z<sub>1</sub>, … , Z<sub>k</sub> 。Z 为 A、B 的最长公共子串，那么就具有一下性质：</p>
<ul>
<li>如果 A<sub>m</sub> = B<sub>n</sub> ：
<ul>
<li>则 Z<sub>k</sub> = A<sub>m</sub> = B<sub>n</sub> ，</li>
<li>且 Z<sub>0</sub> - Z<sub>k-1</sub> 是 A<sub>0</sub> - A<sub>m-1</sub> 与 B<sub>0</sub> - B<sub>n-1</sub> 的最长公共子序列</li>
</ul>
</li>
<li>如果 A<sub>m</sub> != B<sub>n</sub> ：
<ul>
<li>如果 A<sub>m</sub> != Z<sub>k</sub> ：
<ul>
<li>则 Z<sub>0</sub> - Z<sub>k</sub> 是 A<sub>0</sub> - A<sub>m-1</sub> 与 B<sub>0</sub> - B<sub>n</sub> 的最长公共子序列</li>
</ul>
</li>
<li>如果 B<sub>n</sub> != Z<sub>k</sub> ：
<ul>
<li>则 Z<sub>0</sub> - Z<sub>k</sub> 是 A<sub>0</sub> - A<sub>m</sub> 与 B<sub>0</sub> - B<sub>n-1</sub> 的最长公共子序列</li>
</ul>
</li>
</ul>
</li>
</ul>
<p><img src="https://klause-blog-pictures.oss-cn-shanghai.aliyuncs.com/2019-11-19-102625.jpg" alt="img"></p>
<h2 id="递归公式"><a class="header-anchor" href="#递归公式"></a>递归公式</h2>
<p>依据 LCS 的特征，可以发现：</p>
<p>假设需要求（ A<sub>1</sub> - A<sub>m</sub> 和 B<sub>1</sub> - B<sub>n-1</sub>） 的 LCS 与 （A<sub>1</sub> - A<sub>m-1</sub> 和 B<sub>1</sub> - B<sub>n</sub>）的 LCS，一定会将 （A<sub>1</sub> - A<sub>m-1</sub> 和 B<sub>1</sub> - B<sub>n-1</sub>）的 LCS 重复计算几次。所以我们需要一个数据结构来记录中间结果，避免重复计算。</p>
<p>假设用 C[i,j] 表示 X<sub>i</sub> 和 Y<sub>j</sub> 的 LCS 的长度（直接保存最长公共子序列的中间结果不现实，需要先借助 LCS 的长度）。其中 X = {X<sub>1</sub> … X<sub>m</sub>}，Y = {Y<sub>1</sub> … Y<sub>n</sub>}，X<sub>i</sub> = {X<sub>1</sub> … X<sub>i</sub>}，Y<sub>j</sub> = {Y<sub>1</sub> … Y<sub>j</sub>}，可得递归公式如下：</p>
<p><img src="https://klause-blog-pictures.oss-cn-shanghai.aliyuncs.com/2019-11-19-105632.jpg" alt="img"></p>
<h2 id="计算-lcs-的长度"><a class="header-anchor" href="#计算-lcs-的长度"></a>计算 LCS 的长度</h2>
<p>S1 = {1,3,4,5,6,7,7,8}，S2={3,5,7,4,8,6,7,8,2}，借用算法导论中的推导图：</p>
<p><img src="https://klause-blog-pictures.oss-cn-shanghai.aliyuncs.com/2019-11-19-105829.jpg" alt="img"></p>
<p>图中空白格子需要填上相应的数字（这个数字就是 C[i,j] 的定义，记录 LCS 的长度值）。填的规则依据递归公式，简单来说：</p>
<ul>
<li>如果横竖（i，j）对应的两个元素相等，该格子的值 = C[i-1, j-1] + 1</li>
<li>如果不等，取 C[i-1, j] 与 C[i, j-1] 的最大值</li>
</ul>
<p>首先初始化表格：</p>
<p><img src="https://klause-blog-pictures.oss-cn-shanghai.aliyuncs.com/2019-11-19-110104.jpg" alt="img"></p>
<p>然后，一行一行地从上往下填：</p>
<p><img src="https://klause-blog-pictures.oss-cn-shanghai.aliyuncs.com/2019-11-19-110135.jpg" alt="img"></p>
<p>S1 的元素 3 与 S2 的元素 3 相等，所以 C[2, 1] = C[1, 0] + 1。继续填充：</p>
<p><img src="https://klause-blog-pictures.oss-cn-shanghai.aliyuncs.com/2019-11-19-110231.jpg" alt="img"></p>
<p>S1 的元素 3 与 S2 的元素 5 不等，C[2 ,2] = max(C[1, 2], C[2, 1])，图中 C[1, 2] 与 C[2, 1] 背景色为浅黄色。继续填充：</p>
<p><img src="https://klause-blog-pictures.oss-cn-shanghai.aliyuncs.com/2019-11-19-110413.jpg" alt="img"></p>
<p><img src="https://klause-blog-pictures.oss-cn-shanghai.aliyuncs.com/2019-11-19-110422.jpg" alt="img"></p>
<p><img src="https://klause-blog-pictures.oss-cn-shanghai.aliyuncs.com/2019-11-19-110431.jpg" alt="img"></p>
<p>中间几行填写规则不变，直接跳到最后一行：</p>
<p><img src="https://klause-blog-pictures.oss-cn-shanghai.aliyuncs.com/2019-11-19-110457.jpg" alt="img"></p>
<p>至此，该表填完。根据性质，C[8, 9] = S1 和 S2 的 LCS 长度，即为 5。</p>
<h2 id="构造-lcs"><a class="header-anchor" href="#构造-lcs"></a>构造 LCS</h2>
<p>本例 S1 和 S2 的最长 LCS 并不只有 1 个。示例的目的不是输出两个序列的所有 LCS，知识介绍如果通过上表，输出其中一个 LCS。</p>
<p>根据递归公式构建了上表，将从最后一个元素 C[8, 9]倒推出 S1 和 S2 的 LCS。</p>
<p>C[8, 9] = 5，且 S1[8] != S2[9]，所以倒推回去，C[8, 9]的值来源于 C[8, 8] (因为 C[8, 8] &gt; C[7, 9])。</p>
<p>C[8, 8] = 5，且 S1[8] = S2[8]，所以倒推回去，C[8, 8]的值来源于 C[7, 7]。</p>
<p>以此类推，如果遇到 S1[i] != S2[j]，且 C[i-1, j] = C[i, j-1]这种存在分支的情况，就选择其中一个方向（之后遇到这样的情况，也选择相同的方向，只是一种选择，不同选择得到的 LCS 不同，不必深究）</p>
<p>第一种结果为：</p>
<p><img src="https://klause-blog-pictures.oss-cn-shanghai.aliyuncs.com/2019-11-19-111437.jpg" alt="img"></p>
<p>这就是倒推回去的路径，棕色方格为相等的元素，即 LCS = {3,4,6,7,8}，这是其中一个结果。</p>
<p>如果遇到 S1[i] != S2[j] ，且 C[i-1, j ] = C[i, j-1]这种分叉的情况，选择另一个方向，会得到另一个结果。</p>
<p><img src="https://klause-blog-pictures.oss-cn-shanghai.aliyuncs.com/2019-11-19-111644.jpg" alt="img"></p>
<p>即 LCS = {3,5,7,7,8}</p>
<h2 id="时间复杂度"><a class="header-anchor" href="#时间复杂度"></a>时间复杂度</h2>
<p>构建 C[i, j ] 表需要 $O(m*n)$，输出 1 个 LCS 序列需要 $O(m+n)$</p>
<h2 id="python-代码实现"><a class="header-anchor" href="#python-代码实现"></a>Python 代码实现</h2>
<pre><code class="language-python">def lcs(text1: str, text2: str) -&gt; int:
    d = [[0] * (len(text2) + 1) for i in range(len(text1) + 1)]  # 构建空的二维列表，相当于表格

    for i in range(1, len(text1) + 1):
        for j in range(1, len(text2) + 1):
            if text1[i - 1] == text2[j - 1]:
                d[i][j] = d[i - 1][j - 1] + 1
            else:
                d[i][j] = max(d[i - 1][j], d[i][j - 1])

    # 测试代码：打印 C[i, j] 表格
    # for item in d:
    #     print(item)
    return d[-1][-1]


if __name__ == '__main__':
    s1 = '13456778'
    s2 = '357486782'
    result = lcs(s1, s2)
    print(result)  # 5
</code></pre>
<p><a href="https://blog.csdn.net/hrn1216/article/details/51534607" target="_blank" rel="noopener">转载</a>：<a href="https://blog.csdn.net/hrn1216/article/details/51534607" target="_blank" rel="noopener">https://blog.csdn.net/hrn1216/article/details/51534607</a></p>

<div id="gitalk-container"></div>
<script src="https://cdn.bootcss.com/blueimp-md5/2.12.0/js/md5.min.js"></script><link rel="stylesheet" href="https://unpkg.com/gitalk/dist/gitalk.css"><script src="https://unpkg.com/gitalk/dist/gitalk.min.js"></script>

		<script>
		var gitalkConfig = {"clientID":"9eb5bc3ac1e1ff3ddac0","clientSecret":"4b7ae28042282281295075c2bf0c97ff1791cfeb","repo":"HexoBlogComments","owner":"Annihilater","admin":["Annihilater"],"distractionFreeMode":false};
	    gitalkConfig.id = md5(location.pathname);
		var gitalk = new Gitalk(gitalkConfig);
	    gitalk.render("gitalk-container");
	    </script>
            </div>
            <hr/>

            

    <div class="reprint" id="reprint-statement">
        
            <div class="reprint__author">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-user">
                        文章作者:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://www.klause.cn" rel="external nofollow noreferrer">湮灭星空</a>
                </span>
            </div>
            <div class="reprint__type">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-link">
                        文章链接:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://www.klause.cn/2019/11/19/suan-fa/1143.zui-chang-gong-gong-zi-xu-lie-longestcommonsubsequence-jian-cheng-lcs-wen-ti/">https://www.klause.cn/2019/11/19/suan-fa/1143.zui-chang-gong-gong-zi-xu-lie-longestcommonsubsequence-jian-cheng-lcs-wen-ti/</a>
                </span>
            </div>
            <div class="reprint__notice">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-copyright">
                        版权声明:
                    </i>
                </span>
                <span class="reprint-info">
                    本博客所有文章除特別声明外，均采用
                    <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a>
                    许可协议。转载请注明来源
                    <a href="https://www.klause.cn" target="_blank">湮灭星空</a>
                    !
                </span>
            </div>
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>复制成功，请遵循本文的转载规则</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">查看</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            
                                <a href="/tags/%E7%AE%97%E6%B3%95/">
                                    <span class="chip bg-color">算法</span>
                                </a>
                            
                                <a href="/tags/%E6%9C%80%E9%95%BF%E5%85%AC%E5%85%B1%E5%AD%90%E4%B8%B2/">
                                    <span class="chip bg-color">最长公共子串</span>
                                </a>
                            
                                <a href="/tags/LCS-%E9%97%AE%E9%A2%98/">
                                    <span class="chip bg-color">LCS 问题</span>
                                </a>
                            
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="/libs/share/css/share.min.css">

<div id="article-share">
    
    
    <div class="social-share" data-sites="twitter,facebook,google,qq,qzone,wechat,weibo,douban,linkedin" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>
    <script src="/libs/share/js/social-share.min.js"></script>
    

    

</div>

                </div>
            </div>
            
        </div>
    </div>

    

    

    

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fas fa-chevron-left"></i>&nbsp;上一篇</div>
            <div class="card">
                <a href="/2019/11/25/scrapy/crawlab-jian-dan-shi-yong-jiao-cheng/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/1.jpg" class="responsive-img" alt="Scrapy/Crawlab 简单使用教程">
                        
                        <span class="card-title">Scrapy/Crawlab 简单使用教程</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            Crawlab 简单使用教程
Crawlab 是基于 Golang 的分布式爬虫官理平台，支持以及多种爬虫框架。
Crawlab 的官方文档虽然有了但是并不是很详细，作为初学者在使用的时候还是踩了一些坑，在此记录下，希望可以帮助到你。
Cr
                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="far fa-clock fa-fw icon-date"></i>2019-11-25
                        </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-user fa-fw"></i>
                            湮灭星空
                            
                        </span>
                    </div>
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                下一篇&nbsp;<i class="fas fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/2019/11/19/suan-fa/dong-tai-gui-hua-ji-chu-pa-lou-ti-he-wa-jin-kuang-wen-ti/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/4.jpg" class="responsive-img" alt="动态规划基础：爬楼梯和挖金矿问题">
                        
                        <span class="card-title">动态规划基础：爬楼梯和挖金矿问题</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            动态规划基础：爬楼梯和挖金矿问题
三核心

最优子结构
边界
状态转移方程

问题 1
有一座高度是 10 级台阶的楼梯，从下往上走，每跨一步只能向上 1 级或者2 级台阶。要求使用程序来求出一共有多少种走法？
方法 1
逆向思维：
要走到
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2019-11-19
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/Tech/" class="post-category">
                                    Tech
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/markdown/">
                        <span class="chip bg-color">markdown</span>
                    </a>
                    
                    <a href="/tags/%E5%8A%A8%E6%80%81%E8%A7%84%E5%88%92/">
                        <span class="chip bg-color">动态规划</span>
                    </a>
                    
                    <a href="/tags/%E7%AE%97%E6%B3%95/">
                        <span class="chip bg-color">算法</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>

</div>



<!-- 代码块功能依赖 -->
<script type="text/javascript" src="/libs/codeBlock/codeBlockFuction.js"></script>

<!-- 代码语言 -->

<script type="text/javascript" src="/libs/codeBlock/codeLang.js"></script>

    
<!-- 代码块复制 -->

<script type="text/javascript" src="/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->

<script type="text/javascript" src="/libs/codeBlock/codeShrink.js"></script>


<!-- 代码块折行 -->

<style type="text/css">
code[class*="language-"], pre[class*="language-"] { white-space: pre !important; }
</style>

    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget">
            <div class="toc-title"><i class="far fa-list-alt"></i>&nbsp;&nbsp;目录</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fas fa-list-ul"></i>
    </a>
</div>


<script src="/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            // headingsOffset: -205,
            headingSelector: 'h2, h3, h4, h5, h6'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h2, h3, h4, h5, h6').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).hide();
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).show();
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>

    

</main>


<script src="https://cdn.bootcss.com/mathjax/2.7.5/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
<script>
    MathJax.Hub.Config({
        tex2jax: {inlineMath: [['$', '$'], ['\(', '\)']]}
    });
</script>


    <footer class="page-footer bg-color">
    <div class="container row center-align">
        <div class="col s12 m8 l8 copy-right">
            Copyright&nbsp;&copy;
            <span id="year">年份</span>
            <a href="https://www.klause.cn" target="_blank">湮灭星空</a>
            |&nbsp;Powered by&nbsp;<a href="https://hexo.io/" target="_blank">Hexo</a>
            |&nbsp;Theme&nbsp;<a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">Matery</a>
            <br>
            
            &nbsp;<i class="fas fa-chart-area"></i>&nbsp;站点总字数:&nbsp;<span
                class="white-color">199.2k</span>&nbsp;字
            
            
            
            
            
            
            <span id="busuanzi_container_site_pv">
                |&nbsp;<i class="far fa-eye"></i>&nbsp;总访问量:&nbsp;<span id="busuanzi_value_site_pv"
                    class="white-color"></span>&nbsp;次
            </span>
            
            
            <span id="busuanzi_container_site_uv">
                |&nbsp;<i class="fas fa-users"></i>&nbsp;总访问人数:&nbsp;<span id="busuanzi_value_site_uv"
                    class="white-color"></span>&nbsp;人
            </span>
            
            <br>
            
            <span id="sitetime">载入运行时间...</span>
            <script>
                function siteTime() {
                    window.setTimeout("siteTime()", 1000);
                    var seconds = 1000;
                    var minutes = seconds * 60;
                    var hours = minutes * 60;
                    var days = hours * 24;
                    var years = days * 365;
                    var today = new Date();
                    var startYear = "2019";
                    var startMonth = "6";
                    var startDate = "28";
                    var startHour = "0";
                    var startMinute = "0";
                    var startSecond = "0";
                    var todayYear = today.getFullYear();
                    var todayMonth = today.getMonth() + 1;
                    var todayDate = today.getDate();
                    var todayHour = today.getHours();
                    var todayMinute = today.getMinutes();
                    var todaySecond = today.getSeconds();
                    var t1 = Date.UTC(startYear, startMonth, startDate, startHour, startMinute, startSecond);
                    var t2 = Date.UTC(todayYear, todayMonth, todayDate, todayHour, todayMinute, todaySecond);
                    var diff = t2 - t1;
                    var diffYears = Math.floor(diff / years);
                    var diffDays = Math.floor((diff / days) - diffYears * 365);
                    var diffHours = Math.floor((diff - (diffYears * 365 + diffDays) * days) / hours);
                    var diffMinutes = Math.floor((diff - (diffYears * 365 + diffDays) * days - diffHours * hours) /
                        minutes);
                    var diffSeconds = Math.floor((diff - (diffYears * 365 + diffDays) * days - diffHours * hours -
                        diffMinutes * minutes) / seconds);
                    if (startYear == todayYear) {
                        document.getElementById("year").innerHTML = todayYear;
                        document.getElementById("sitetime").innerHTML = "本站已安全运行 " + diffDays + " 天 " + diffHours +
                            " 小时 " + diffMinutes + " 分钟 " + diffSeconds + " 秒";
                    } else {
                        document.getElementById("year").innerHTML = startYear + " - " + todayYear;
                        document.getElementById("sitetime").innerHTML = "本站已安全运行 " + diffYears + " 年 " + diffDays +
                            " 天 " + diffHours + " 小时 " + diffMinutes + " 分钟 " + diffSeconds + " 秒";
                    }
                }
                setInterval(siteTime, 1000);
            </script>
            
            <br>
            
            <span id="icp"><img src="/medias/icp.png" style="vertical-align: text-bottom;" />
                <a href="http://www.beian.miit.gov.cn" target="_blank">皖ICP备18005729号-1</a>
            </span>
            
        </div>
        <div class="col s12 m4 l4 social-link social-statis">
    <a href="https://github.com/Annihilater" class="tooltipped" target="_blank" data-tooltip="访问我的GitHub" data-position="top" data-delay="50">
        <i class="fab fa-github"></i>
    </a>



    <a href="mailto:yanmiexingkong@gmail.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">
        <i class="fas fa-envelope-open"></i>
    </a>





    <a href="https://twitter.com/" class="tooltipped" target="_blank" data-tooltip="关注我的Twitter: https://twitter.com/" data-position="top" data-delay="50">
        <i class="fab fa-twitter"></i>
    </a>







    <a href="https://www.zhihu.com/" class="tooltipped" target="_blank" data-tooltip="关注我的知乎: https://www.zhihu.com/" data-position="top" data-delay="50">
        <i class="fab fa-zhihu1">知</i>
    </a>



    <a href="/atom.xml" class="tooltipped" target="_blank" data-tooltip="RSS 订阅" data-position="top" data-delay="50">
        <i class="fas fa-rss"></i>
    </a>

</div>
    </div>
</footer>

<div class="progress-bar"></div>

    <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script src="/js/search.js"></script>
<script type="text/javascript">
$(function () {
    searchFunc("/" + "search.xml", 'searchInput', 'searchResult');
});
</script>
    <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>


    <script src="/libs/materialize/materialize.min.js"></script>
    <script src="/libs/masonry/masonry.pkgd.min.js"></script>
    <script src="/libs/aos/aos.js"></script>
    <script src="/libs/scrollprogress/scrollProgress.min.js"></script>
    <script src="/libs/lightGallery/js/lightgallery-all.min.js"></script>
    <script src="/js/matery.js"></script>

    <!-- Global site tag (gtag.js) - Google Analytics -->


    <!-- Baidu Analytics -->

    <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

    
    <script src="/libs/others/clicklove.js" async="async"></script>
    
    
    <script async src="/libs/others/busuanzi.pure.mini.js"></script>
    

    

    

    

    

    
    <script type="text/javascript" src="/libs/background/ribbon-dynamic.js" async="async"></script>
    
    
    
    <script src="/libs/instantpage/instantpage.js" type="module"></script>
    

</body>

</html>
